package city.spring.modules.medicine.controller;

import city.spring.modules.medicine.entity.MedicineInventoryEntity;
import city.spring.modules.medicine.entity.MedicineinventoryMedicineExtEntity;
import city.spring.modules.medicine.repository.MedicineinventoryMedicineExtRepository;
import city.spring.modules.medicine.service.MedicineInventoryService;
import city.spring.modules.medicine.service.MedicineinventoryMedicineExtService;
import city.spring.modules.medicine.vo.MedicineinventoryMedicineVO;
import city.spring.utils.MyBatisUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Controller：药品盘点计划与药品关系表
 *
 * @author 谢金婷
 * @date 2020-07-27 09:44:32
 */
@RestController
@RequestMapping("/medicineinventory/{inventoryId}/medicine")
public class MedicineInventoryMedicineExtController extends ApiController {
    private final MedicineinventoryMedicineExtService medicineinventoryMedicineExtService;
    private final MedicineinventoryMedicineExtRepository medicineinventoryMedicineExtRepository;
    private final MedicineInventoryService medicineInventoryService;
    /**
     * 实体类可排序字段
     */
    private final List<SFunction<MedicineinventoryMedicineExtEntity, ?>> entityOrderFields;

    public MedicineInventoryMedicineExtController(MedicineinventoryMedicineExtService medicineinventoryMedicineExtService, MedicineinventoryMedicineExtRepository medicineinventoryMedicineExtRepository, MedicineInventoryService medicineInventoryService) {
        this.medicineinventoryMedicineExtService = medicineinventoryMedicineExtService;
        this.medicineinventoryMedicineExtRepository = medicineinventoryMedicineExtRepository;
        this.medicineInventoryService = medicineInventoryService;
        entityOrderFields = new ArrayList<>();
        entityOrderFields.add(MedicineinventoryMedicineExtEntity::getId);
        entityOrderFields.add(MedicineinventoryMedicineExtEntity::getMedicineinventoryId);
        entityOrderFields.add(MedicineinventoryMedicineExtEntity::getStorehouseId);
        entityOrderFields.add(MedicineinventoryMedicineExtEntity::getShelfId);
        entityOrderFields.add(MedicineinventoryMedicineExtEntity::getMedicineId);
        entityOrderFields.add(MedicineinventoryMedicineExtEntity::getQuantity);
        entityOrderFields.add(MedicineinventoryMedicineExtEntity::getInventoryquantity);
        entityOrderFields.add(MedicineinventoryMedicineExtEntity::getProfitAndLoss);
    }

    @ModelAttribute
    public void getInventoryId(@PathVariable String inventoryId) {
        if (inventoryId == null) {
            throw new RuntimeException("盘点计划ID必须不为空");
        }
    }

    /**
     * 获取全部的 <strong>药品盘点计划与药品关系表</strong> 列表
     */
    @GetMapping("all")
    public Object listAll(@PageableDefault Pageable pageable, MedicineinventoryMedicineExtEntity entity) {
        LambdaQueryChainWrapper<MedicineinventoryMedicineExtEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        return success(lambdaQuery.list());
    }

//    /**
//     * 分页获取 <strong>药品盘点计划与药品关系表</strong> 列表
//     *
//     * @param pageable 分页参数信息
//     */
//    @GetMapping
//    public Object list(@PageableDefault Pageable pageable, MedicineinventoryMedicineExtEntity entity) {
//        LambdaQueryChainWrapper<MedicineinventoryMedicineExtEntity> lambdaQuery = buildLambdaQuery(entity);
//        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
//        Page<MedicineinventoryMedicineExtEntity> page = lambdaQuery.page(MyBatisUtils.toPage(pageable, false));
//        return success(page);
//    }

    /**
     * 获取盘点计划所有人员列表
     *
     * @param inventoryId 盘点计划ID
     */
    @GetMapping
    public Object list(@PathVariable String inventoryId) {
        return success(medicineinventoryMedicineExtRepository.getInventoryMedicines(inventoryId));
    }

//    /**Medicine
//     * 获取一个 <strong>药品盘点计划与药品关系表</strong>
//     *
//     * @param id 主键ID
//     */
//    @GetMapping("{id}")
//    public Object info(@PathVariable String id) {
//        return success(medicineinventoryMedicineExtService.getById(id));
//    }

    /**
     * 获取方案的一个人员信息
     *
     * @param inventoryId 方案ID
     * @param extId       关联ID
     * @return
     */
    @GetMapping("{extId}")
    public Object getInfo(@PathVariable String inventoryId, @PathVariable Long extId) {
        return success(medicineinventoryMedicineExtRepository.getInventoryMedicine(inventoryId, extId));
    }

//    /**
//     * 添加一个 <strong>药品盘点计划与药品关系表</strong>
//     *
//     * @param entity 修改后的信息
//     */
//    @PostMapping
//    public Object add(@RequestBody MedicineinventoryMedicineExtEntity entity) {
//        medicineinventoryMedicineExtService.saveMedicineinventoryMedicineExt(entity);
//
//        HttpHeaders headers = new HttpHeaders();
//        headers.add(HttpHeaders.LOCATION, String.valueOf(entity.getId()));
//        return new ResponseEntity<>(headers, HttpStatus.CREATED);
//    }

    /**
     * 给方案添加多个人员信息
     *
     * @param inventoryId 方案ID
     * @param medicines   所添加的人员信息列表
     * @return
     */
    @PostMapping
    public Object addAll(@PathVariable String inventoryId, @RequestBody List<MedicineinventoryMedicineExtEntity> medicines) {
        // 查出已有的数据
        List<MedicineinventoryMedicineVO> dbMedicines = medicineinventoryMedicineExtRepository.getInventoryMedicines(inventoryId);
        // 数据库已经存在的班次列表
        Set<String> dbMedicineIdsSet = dbMedicines.stream()
                .map(MedicineinventoryMedicineExtEntity::getMedicineId)
                .collect(Collectors.toSet());
        // 过滤掉已经存在数据库的数据
        List<MedicineinventoryMedicineExtEntity> needSaveMedicines = medicines.stream()
                .filter(item -> {
                    item.setMedicineinventoryId(inventoryId);
                    String medicineId = item.getMedicineId();
                    // 过滤出不存在数据库中的数据
                    return medicineId != null && !dbMedicineIdsSet.contains(medicineId);
                }).collect(Collectors.toList());
        if (!needSaveMedicines.isEmpty()) {
            medicineinventoryMedicineExtService.saveBatch(needSaveMedicines);
        }

        return success(null);

    }

//    /**
//     * 修改一个 <strong>药品盘点计划与药品关系表</strong>
//     *
//     * @param id     主键ID
//     * @param entity 修改后的信息
//     */
//    @PutMapping("{id}")
//    public Object update(@PathVariable String id, @RequestBody MedicineinventoryMedicineExtEntity entity) {
//        entity.setId(id);
//        medicineinventoryMedicineExtService.updateMedicineinventoryMedicineExt(entity);
//        return new ResponseEntity<>(HttpStatus.OK);
//    }

    /**
     * 修改一个方案关联的人员信息
     *
     * @param inventoryId 方案ID
     * @param extId       关联ID
     * @param extEntity   接收的数据
     * @return
     */
    @PutMapping("{extId}")
    public Object update(@PathVariable String inventoryId, @PathVariable Long extId, @RequestBody MedicineinventoryMedicineExtEntity extEntity) {
        extEntity.setId(String.valueOf(extId));
        extEntity.setMedicineinventoryId(inventoryId);
        medicineinventoryMedicineExtService.updateMedicineinventoryMedicineExt(extEntity);

        /**
         * 计算损益值
         */
        List<MedicineinventoryMedicineExtEntity> medicinesInventorys = medicineinventoryMedicineExtRepository.getMedicinesByInventoryId(inventoryId);
//        System.out.println("medicinesInventorys"+medicinesInventorys);
        for (MedicineinventoryMedicineExtEntity medicineEntity : medicinesInventorys) {
            System.out.println("medicineEntity" + medicineEntity);
            medicineEntity.setProfitAndLoss(medicineEntity.getInventoryquantity().subtract(medicineEntity.getQuantity()));
            // 设置盘点时间
            medicineEntity.setInventorydate(new Date());
            medicineinventoryMedicineExtService.lambdaUpdate()
                    .set(MedicineinventoryMedicineExtEntity::getProfitAndLoss, medicineEntity.getProfitAndLoss())
                    .set(MedicineinventoryMedicineExtEntity::getInventorydate, medicineEntity.getInventorydate())
                    .eq(MedicineinventoryMedicineExtEntity::getId, medicineEntity.getId())
                    .update();
            System.out.println("sfasda" + medicineEntity.getProfitAndLoss());


            MedicineInventoryEntity medicineInventoryEntity = medicineInventoryService.getById(inventoryId);
            medicineInventoryEntity.setIsInventory(2);
            medicineInventoryService.lambdaUpdate()
                    .set(MedicineInventoryEntity::getIsInventory, medicineInventoryEntity.getIsInventory())
                    .eq(MedicineInventoryEntity::getId, medicineInventoryEntity.getId())
                    .update();
        }


        return success(null);
    }

    /**
     * 删除一个 <strong>药品盘点计划与药品关系表</strong>
     *
     * @param id 主键ID
     */
    @DeleteMapping("{id}")
    public Object delete(@PathVariable String id) {
        medicineinventoryMedicineExtService.deleteMedicineinventoryMedicineExt(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 删除多个 <strong>药品盘点计划与药品关系表</strong>
     *
     * @param ids 主键ID列表
     */
    @DeleteMapping
    public Object deleteIds(@RequestBody List<String> ids) {
        medicineinventoryMedicineExtService.deleteMedicineinventoryMedicineExt(ids);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private LambdaQueryChainWrapper<MedicineinventoryMedicineExtEntity> buildLambdaQuery(MedicineinventoryMedicineExtEntity entity) {
        LambdaQueryChainWrapper<MedicineinventoryMedicineExtEntity> lambdaQuery = medicineinventoryMedicineExtService.lambdaQuery();
        lambdaQuery.eq(StringUtils.isNotBlank(entity.getId()), MedicineinventoryMedicineExtEntity::getId, entity.getId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getMedicineinventoryId()), MedicineinventoryMedicineExtEntity::getMedicineinventoryId, entity.getMedicineinventoryId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getStorehouseId()), MedicineinventoryMedicineExtEntity::getStorehouseId, entity.getStorehouseId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getShelfId()), MedicineinventoryMedicineExtEntity::getShelfId, entity.getShelfId());
        lambdaQuery.eq(entity.getMedicineId() != null, MedicineinventoryMedicineExtEntity::getMedicineId, entity.getMedicineId());
        lambdaQuery.eq(entity.getQuantity() != null, MedicineinventoryMedicineExtEntity::getQuantity, entity.getQuantity());
        lambdaQuery.eq(entity.getInventoryquantity() != null, MedicineinventoryMedicineExtEntity::getInventoryquantity, entity.getInventoryquantity());
        lambdaQuery.eq(entity.getProfitAndLoss() != null, MedicineinventoryMedicineExtEntity::getProfitAndLoss, entity.getProfitAndLoss());
        return lambdaQuery;
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private QueryWrapper<MedicineinventoryMedicineExtEntity> buildQuery(MedicineinventoryMedicineExtEntity entity) {
        QueryWrapper<MedicineinventoryMedicineExtEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(entity.getId()), "id", entity.getId());
        wrapper.like(StringUtils.isNotBlank(entity.getMedicineinventoryId()), "medicineinventory_id", entity.getMedicineinventoryId());
        wrapper.like(StringUtils.isNotBlank(entity.getStorehouseId()), "storehouse_id", entity.getStorehouseId());
        wrapper.like(StringUtils.isNotBlank(entity.getShelfId()), "shelf_id", entity.getShelfId());
        wrapper.eq(entity.getMedicineId() != null, "medicine_id", entity.getMedicineId());
        wrapper.eq(entity.getQuantity() != null, "quantity", entity.getQuantity());
        wrapper.eq(entity.getInventoryquantity() != null, "inventoryquantity", entity.getInventoryquantity());
        wrapper.eq(entity.getProfitAndLoss() != null, "profit_and_loss", entity.getProfitAndLoss());
        return wrapper;
    }

}
